<?php
class UsersController extends AppController {
	public $name          = 'Users';
    public $components    = array('Auth', 'Email');
    public $publicActions = array('confirmation', 'forgot', 'register', 'resetPassword', 'signup');


    public function beforeFilter () {
        parent::beforeFilter();
        $this->checkAuth();
    } // beforeFilter

    public function admin_index () {
        $this->set('users', $this->paginate());
    } // admin_index

    public function admin_add () {
        if ($this->data) {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash('<h4>'.__('New user has been saved',true).'</h4>', 'default', array('class'=>'boxSuccess'));
                $this->redirect('/admin/users/add');
            }
        }

        $this->data['User']['password'] = '';
        $this->pageTitle = __('Add New User', true);
    } // admin_add

    public function admin_edit ($id) {
        if (empty($this->data)) {
            if (!$id) {
                $this->flash('<h4>'.__('Missing required id',true).'</h4>', 'index', 5);
            } else {
                $this->data = $this->User->findById($id);
            }
        } else {
            if ($this->User->save($this->data)) {
                $this->flash('<h4>'.__('The User has been saved.',true).'</h4>', 'index');
            }
        }

        $this->pageTitle = __('Edit User', true);
    } // admin_edit

    public function forgot () {
        if ($this->data && !$this->data['User']['email']) {
            $this->Session->setFlash('<h4>'.__('Email address field is required',true).'</h4>', 'default', array('class'=>'boxError'));
        } else if ($email = $this->data['User']['email']) {
            if ($this->User->isEmailTaken($email)) {
                $this->_sendResetPassword($email);
                $mesg = __('An email has been sent to %email% describing how to obtain your new password.', true);
                $mesg = r('%email%', $email, $mesg);
                $this->Session->setFlash('<h4>'.$mesg.'</h4>', 'default', array('class'=>'boxAtt'));
            } else { // email does not exists
                $inst = __('The email address you entered has not been registered.', true);
                $this->Session->setFlash('<h4>'.__('Unregistered Email',true).'</h4>'.$inst, 'default', array('class'=>'boxError'));
            }
        }
    } // forgot

    public function resetPassword ($id=null, $code=null) {
        $inst = __('The link that you followed was invalid or incomplete. Try copying and pasting the full link into the address bar.', true);

        if (!$id || !$code) {
            $this->Session->setFlash('<h4>'.__('Invalid Link',true).'</h4>'.$inst, 'default', array('class'=>'boxError'));
            $this->redirect('/users/forgot');
        } else {
            $password = $this->User->field('password', array('id'=>$id));
            $secret   = Configure::read('Security.salt');
            $secret   = md5($password.$secret);

            if ($secret != $code) {
                $this->Session->setFlash('<h4>'.__('Invalid Link',true).'</h4>'.$inst, 'default', array('class'=>'boxError'));
                $this->redirect('/users/forgot');
            } else if ($this->data) {
                unset($inst);
                if (!$this->data['User']['password1'] || !$this->data['User']['password2']) {
                    $inst = __('Your password cannot be blank. Please try another.', true);
                } else if ($this->data['User']['password1'] != $this->data['User']['password2']) {
                    $inst = __('You must enter the same password twice in order to confirm it.', true);
                } else if (strlen($this->data['User']['password1']) < 6) {
                    $inst = __('Your password must be at least 6 characters long. Please try another.', true);
                }
                if ($inst) {
                    $this->Session->setFlash('<h4>'.__('Password Error',true).'</h4>'.$inst, 'default', array('class'=>'boxError'));
                } else {
                    $inst = __('You may Sign In by using new password now', true);
                    $newpassword = $this->Auth->password($this->data['User']['password1']);
                    $this->User->id = $id;
                    $this->User->saveField('password', $newpassword);
                    $this->Session->setFlash('<h4>'.__('Password has changed successfully',true).'</h4>'.$inst, 'default', array('class'=>'boxSuccess'));
                    $this->redirect('/users/login');
                }
            }
        }

        $this->pageTitle = __('Reset Password', true);
        $this->set('link', Router::url('/users/resetPassword/'.$id.'/'.$code, true));
    } // resetPassword

    public function register () {
        if ($this->data) {
            $valid = true;
            $this->User->set($this->data);

            if (!$this->data['User']['password2']) {
                $valid = false;
                $this->data['User']['password'] = '';
                $this->User->validationErrors['password2'] = __('Please Re-type password', true);
            } else if ($this->data['User']['password'] != $this->Auth->password($this->data['User']['password2'])) {
                $valid = false;
                $this->data['User']['password'] = '';
                $this->User->validationErrors['password2'] = __('Your password did not match', true);
            }

            if ($this->User->validates() && $valid) { // data validated!
                if ($id = $this->Cookie->read('User.id')) { // auto registered before
                    $this->User->id = $id;
                    if ($this->User->field('active') == 1) { // already has active account, maybe request for new account registration
                        $this->User->id = null;
                    }
                }
                if (empty($this->data['User']['newsletter'])) {
                    $this->data['User']['newsletter'] = 0;
                }
                if ($this->_validateEmail() && $this->User->save($this->data)) {
                    $this->Cookie->write('User.id', $this->User->id, true, '1 year');
                    $this->_sendActivationMail($this->data['User']['nickname'], $this->data['User']['email'], $this->User->id);
                    $this->Session->setFlash('<h4>'.__('Registration has been done',true).'</h4>', 'default', array('class'=>'boxSuccess'));
                    $this->redirect('/users/signup');
                } else {
                    $this->data['User']['password'] = '';
                }
            } else {
                $this->Session->setFlash('<h4>'.__('Please enter the requested details in the fields pointed out below and try again!',true).'</h4>', 'default', array('class'=>'boxError'));
            }
        } else {
            $this->data['User']['email'] = $this->Cookie->read('User.email'); // email saved in cookie before?
        }

        $this->pageTitle = __('Start Registration', true);
    } // register

    public function signup () {
        $this->helpers[] = 'Text';
        $this->pageTitle = __('Account Signup', true);
        $this->set('email', $this->Cookie->read('User.email'));
        $this->set('helpmail', Configure::read('site.email'));
    } // signup

    public function confirmation ($id=null, $code=null) {
        if (!$id || !$code) {
            $this->set('pageTitle', __('Missing user id or confirmation code.',true));
            $this->flash('<h4>'.__('Missing user id or confirmation code.',true).'</h4>', '/', 8);
            return false;
        }

        $secret = Configure::read('Security.salt');
        $secret = md5($id.$secret);

        if ($code != $secret) {
            $inst = __('The confirmation link you clicked is invalid or incomplete. Try copying and pasting the full link into your web browser\'s address bar.', true);
            $this->set('pageTitle', __('Invalid Link.',true));
            $this->flash('<h4>'.__('Invalid Link.',true).'</h4><small>'.$inst.'</small>', '/', 30);
            return false;
        }

        $active = $this->User->field('active', array('id'=>$id));

        if (!$active) {
            $this->User->id = $id;
            $this->User->saveField('active', 1);
            $message = r('%sitename%', Configure::read('site.sitename'), __('Thank you for registering with %sitename%. Have fun!',true));
        } else {
            $this->flash('<h4>'.__('You are already registered.',true).'</h4>', '/users/home', 5);
        }

        $this->Session->setFlash('<h4>'.$message.'</h4>', 'default', array('class'=>'boxSuccess'));
        $this->redirect('/users/login');
    } // confirmation

    public function login () {
        if ($id = $this->Auth->user('id')) { // successful logged
            $this->Cookie->write('User.id', $id, true, '1 year');
            $this->Cookie->write('User.email', $this->Auth->user('email'), true, '1 year');

            $nickname = $this->Auth->user('nickname');
            $nickname = $nickname ? ' '.$nickname : '';
            $greeting = r('%nickname%', $nickname, __('Hi%nickname%, Welcome back!', true));

            $url = ($this->Auth->user('role') == 'admin') ? '/admin/pages/cpanel' : $this->Auth->redirect();
            $this->Session->setFlash('<h4>'.$greeting.'</h4>', 'default', array('class'=>'boxNotice'));
            $this->redirect($url);
        } else if (!empty($this->data)) { // invalid login has made
            $err = '<h4>'.__('Sorry, the email address and password combination is incorrect. Please try again.', true).'</h4>' .
                   __('Don\'t forget that you can still post Ads without being signed in.', true);
            $this->Session->del('Message.auth');
            $this->Session->setFlash($err, 'default', array('class'=>'boxError'));
        } else { // user has not logged
            $this->data['User']['email'] = $this->Cookie->read('User.email');
        }
    } // login

    public function logout () {
        $this->Session->setFlash('<h4>'.__('Good-Bye and see you again..',true).'</h4>', 'default', array('class'=>'boxNotice'));
        $this->Auth->logout();
        $this->redirect('/');
    } // logout

    public function home () {
    } // public


    private function _validateEmail () {
        $email = $this->Cookie->read('User.email');

        if (!$email || $email != $this->data['User']['email']) { // no email record in cookie OR has change different email
            if ($this->User->isEmailTaken($this->data['User']['email'])) { // email has already been taken
                $link = '<a href="'.$this->base.'/users/forgot">'.__('here',true).'</a>';
                $err  = __('There is an existing account associated with %email%', true);
                $err  = r('%email%', $this->data['User']['email'], $err);
                $inst = __('You can only sign up for one %sitename% account per email address. If you\'ve forgotten your password, you can reset it %link%. You can also sign up with a different email address below.', true);
                $inst = str_replace(array('%sitename%','%link%'), array(Configure::read('site.sitename'),$link), $inst);
                $this->Session->setFlash('<h4>'.$err.'</h4>'.$inst, 'default', array('class'=>'boxError'));
                return false;
            }
        }

        return true;
    } // _validateEmail

    private function _sendActivationMail ($name, $email, $id) {
        $sitename = Configure::read('site.sitename');
        $sitename = __($sitename, true);
        $title    = r('%sitename%', $sitename, __('Complete your %sitename% registration',true));
        $delivery = (Configure::read('debug') > 1) ? 'debug' : 'mail';

        $this->Email->to       = $email;
        $this->Email->replyTo  = 'noreply@'.env('HTTP_HOST');
        $this->Email->from     = $sitename.' <noreply@'.env('HTTP_HOST').'>';
        $this->Email->subject  = $title;
        $this->Email->template = 'activation';
        $this->Email->sendAs   = 'both';
        $this->Email->delivery = $delivery;

        $secret = Configure::read('Security.salt');
        $code   = md5($id.$secret);
        $name   = ($name) ? ' '.$name : '';
        $data   = array(
            'name'     => $name,
            'url'      => Router::url('/users/confirmation/'.$id.'/'.$code, true),
            'sitename' => $sitename
        );

        $this->set($data);
        $this->Email->send();
    } // _sendActivationMail

    private function _sendResetPassword ($email) {
        $sitename = Configure::read('site.sitename');
        $sitename = __($sitename, true);
        $title    = r('%sitename%', $sitename, __('Reset your password on %sitename%',true));
        $delivery = (Configure::read('debug') > 1) ? 'debug' : 'mail';

        $this->Email->to       = $email;
        $this->Email->replyTo  = 'noreply@'.env('HTTP_HOST');
        $this->Email->from     = $sitename.' <noreply@'.env('HTTP_HOST').'>';
        $this->Email->subject  = $title;
        $this->Email->template = 'reset_password';
        $this->Email->sendAs   = 'text';
        $this->Email->delivery = $delivery;

        $params = array(
            'conditions' => array('email'=>$email),
            'recursive'  => -1
        );
        $data = $this->User->find('first', $params);
        $id   = $data['User']['id'];
        $name = ($data['User']['nickname']) ? ' '.$data['User']['nickname'] : '';

        $secret = Configure::read('Security.salt');
        $code   = md5($data['User']['password'].$secret);

        $data   = array(
            'name'     => $name,
            'url'      => Router::url('/users/resetPassword/'.$id.'/'.$code, true),
            'sitename' => $sitename
        );

        $this->set($data);
        $this->Email->send();
    } // _sendResetPassword
} // UsersController
?>